// Package integrity provides data integrity checking and verification
package integrity

import (
	"context"
	"time"
)

// HashAlgorithm represents supported hash algorithms
type HashAlgorithm string

const (
	// SHA256 represents SHA-256 hash algorithm
	SHA256 HashAlgorithm = "sha256"
	// BLAKE3 represents BLAKE3 hash algorithm
	BLAKE3 HashAlgorithm = "blake3"
)

// IntegrityChecker provides data integrity checking functionality
type IntegrityChecker interface {
	// CalculateHash calculates hash for given data using specified algorithm
	CalculateHash(ctx context.Context, data []byte, algorithm HashAlgorithm) (string, error)

	// VerifyHash verifies data against expected hash
	VerifyHash(ctx context.Context, data []byte, expectedHash string, algorithm HashAlgorithm) error

	// CalculateFileHash calculates hash for a file
	CalculateFileHash(ctx context.Context, filePath string, algorithm HashAlgorithm) (string, error)

	// VerifyFileHash verifies file against expected hash
	VerifyFileHash(ctx context.Context, filePath string, expectedHash string, algorithm HashAlgorithm) error
}

// ChecksumCalculator provides checksum calculation functionality
type ChecksumCalculator interface {
	// CalculateChecksum calculates checksum for data
	CalculateChecksum(data []byte) []byte

	// VerifyChecksum verifies data against expected checksum
	VerifyChecksum(data []byte, expectedChecksum []byte) error
}

// IntegrityMetadata stores integrity information
type IntegrityMetadata struct {
	// Hash value calculated using specified algorithm
	Hash string `json:"hash"`
	// Algorithm used for hash calculation
	Algorithm HashAlgorithm `json:"algorithm"`
	// Checksum for additional verification
	Checksum []byte `json:"checksum,omitempty"`
	// Size of the original data
	Size int64 `json:"size"`
	// Creation timestamp
	CreatedAt time.Time `json:"created_at"`
	// Last verification timestamp
	LastVerifiedAt time.Time `json:"last_verified_at,omitempty"`
	// Verification status
	Status VerificationStatus `json:"status"`
}

// VerificationStatus represents the status of integrity verification
type VerificationStatus string

const (
	// StatusVerified indicates data is verified and valid
	StatusVerified VerificationStatus = "verified"
	// StatusCorrupted indicates data is corrupted
	StatusCorrupted VerificationStatus = "corrupted"
	// StatusUnknown indicates verification status is unknown
	StatusUnknown VerificationStatus = "unknown"
)

// IntegrityManager manages data integrity across the system
type IntegrityManager interface {
	// StoreIntegrityMetadata stores integrity metadata for data
	StoreIntegrityMetadata(ctx context.Context, key string, metadata *IntegrityMetadata) error

	// LoadIntegrityMetadata loads integrity metadata
	LoadIntegrityMetadata(ctx context.Context, key string) (*IntegrityMetadata, error)

	// VerifyIntegrity verifies data integrity
	VerifyIntegrity(ctx context.Context, key string, data []byte) error

	// VerifyFileIntegrity verifies file integrity
	VerifyFileIntegrity(ctx context.Context, key string, filePath string) error

	// MarkAsCorrupted marks data as corrupted
	MarkAsCorrupted(ctx context.Context, key string, reason string) error

	// GetCorruptedData returns list of corrupted data keys
	GetCorruptedData(ctx context.Context) ([]string, error)

	// ScheduleVerification schedules periodic verification
	ScheduleVerification(ctx context.Context, key string, interval time.Duration) error
}

// RecoveryHandler handles data recovery when corruption is detected
type RecoveryHandler interface {
	// RecoverData attempts to recover corrupted data
	RecoverData(ctx context.Context, key string, metadata *IntegrityMetadata) ([]byte, error)

	// HasBackup checks if backup exists for given key
	HasBackup(ctx context.Context, key string) bool

	// CreateBackup creates backup for data
	CreateBackup(ctx context.Context, key string, data []byte) error

	// RestoreFromBackup restores data from backup
	RestoreFromBackup(ctx context.Context, key string) ([]byte, error)

	// GetRecoveryStats returns recovery statistics
	GetRecoveryStats(ctx context.Context) (*RecoveryStats, error)
}

// RecoveryStats contains recovery statistics
type RecoveryStats struct {
	// Total number of recovery attempts
	TotalAttempts int64 `json:"total_attempts"`
	// Number of successful recoveries
	SuccessfulRecoveries int64 `json:"successful_recoveries"`
	// Number of failed recoveries
	FailedRecoveries int64 `json:"failed_recoveries"`
	// Last recovery timestamp
	LastRecoveryAt time.Time `json:"last_recovery_at,omitempty"`
}

// VerificationResult contains the result of integrity verification
type VerificationResult struct {
	// Whether verification passed
	Valid bool `json:"valid"`
	// Error message if verification failed
	Error string `json:"error,omitempty"`
	// Hash algorithm used
	Algorithm HashAlgorithm `json:"algorithm"`
	// Expected hash value
	ExpectedHash string `json:"expected_hash"`
	// Actual hash value calculated
	ActualHash string `json:"actual_hash"`
	// Verification timestamp
	VerifiedAt time.Time `json:"verified_at"`
}

// IntegrityConfig contains configuration for integrity checking
type IntegrityConfig struct {
	// Default hash algorithm to use
	DefaultAlgorithm HashAlgorithm `json:"default_algorithm"`
	// Whether to calculate additional checksum
	EnableChecksum bool `json:"enable_checksum"`
	// Whether to enable automatic recovery
	EnableRecovery bool `json:"enable_recovery"`
	// Verification interval for periodic checks
	VerificationInterval time.Duration `json:"verification_interval"`
	// Maximum number of recovery attempts
	MaxRecoveryAttempts int `json:"max_recovery_attempts"`
	// Whether to create backups
	EnableBackup bool `json:"enable_backup"`
}